package com.th.controller;

import com.th.Service.UserService;
import com.th.pojo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.servlet.http.HttpServletRequest;

//表示该控制器所有方法都返回纯数据
@RestController
//Session数据的存放
@SessionAttributes(names = "user", types = User.class)
public class UserController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @Autowired
    UserService userService;

    @PostMapping("/login")
    public String login(Model model, HttpServletRequest request, String username, String password, String vcode, boolean rememberMe){
        String sessionVCODE = (String) SecurityUtils.getSubject().getSession().getAttribute(VerificationController.VCODE);
        if (null == vcode || !vcode.equalsIgnoreCase(sessionVCODE)) {
            return "2";
        }
        //如果有点击  记住我
        UsernamePasswordToken userToken = new UsernamePasswordToken(username, password, rememberMe);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(userToken);
            Subject currentSubject = SecurityUtils.getSubject();
            Session session = currentSubject.getSession();
            session.setAttribute("loginUser", (User) currentSubject.getPrincipal());
            return "1";
        } catch (Exception e) {
            //登录失败从request中获取shiro处理的异常信息 shiroLoginFailure:就是shiro异常类的全类名
            String exception = (String) request.getAttribute("shiroLoginFailure");
            if (e instanceof UnknownAccountException) {
                return "0";
            }

            if (e instanceof IncorrectCredentialsException) {
                return "0";
            }

            if (e instanceof LockedAccountException) {
                return "3";
            }
        }
        return "0";
    }
}
